<template>
  <div id="main">
    <h2>班级管理</h2>
    <el-button
      type="primary"
      style="margin:20px"
      @click="handleOpen('添加班级', 1)"
    >添加班级</el-button>
    <!-- -------------------------------------列表展示区-------------------------------------------------------------------- -->
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="
          list
            .slice((currentPage - 1) * pagesize, currentPage * pagesize)
            .filter(
              data =>
                !search ||
                String(data.className)
                  .toLowerCase()
                  .includes(search.toLowerCase()) ||
                data.startTime.toLowerCase().includes(search.toLowerCase())
            )
        "
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="序号" type="index" align="center">
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="className" label="班级名称" />

        <el-table-column align="center" prop="classType" label="班级类型">
          <template slot-scope="scope">
            <span v-if="scope.row.classType == '0'">普通班级</span>
            <span v-if="scope.row.classType == '1'">特殊班级</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="startTime"
          :formatter="dateFormat"
          label="班级开始时间"
        />
        <el-table-column
          align="center"
          prop="endTime"
          :formatter="dateFormat"
          label="班级结束时间"
        />
        <el-table-column align="center" prop="classStatus" label="课程状态">
          <template slot-scope="scope">
            <span v-if="scope.row.classStatus == '0'">未开始</span>
            <span v-if="scope.row.classStatus == '1'">已结束</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot="header" slot-scope="scope">
            <el-input
              v-model="search"
              size="mini"
              placeholder="输入关键字搜索"
            />
          </template>
          <template slot-scope="Scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleOpen('修改班级', 2, Scope.row.classId)"
            >编辑/查看</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(Scope.row.classId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- -------------------------------------列表展示区-------------------------------------------------------------------- -->

    <!-- -------------------------------------添加信息区-------------------------------------------------------------------- -->
    <el-dialog
      title=""
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form ref="clazz" :model="clazz" label-position="top" :rules="rules">
        <el-form-item
          prop="className"
          label="班级名称"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="clazz.className"
            autocomplete="off"
            maxlength="20"
            show-word-limit
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          prop="classResponsibleTeacherId"
          label="责任老师姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-if="editType == 1"
            v-model="clazz.classResponsibleTeacherId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff3"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
          <el-select
            v-if="editType == 2"
            v-model="clazz.classResponsibleTeacherId"
            disabled
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff3"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classTeacherId"
          label="授课老师姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classTeacherId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff4"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classMedicalDirectorId"
          label="医疗主管姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classMedicalDirectorId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff5"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classTeachingDirectorId"
          label="教学主管姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classTeachingDirectorId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff2"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classCourseId"
          label="课程名称"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classCourseId"
            placeholder="请选择"
            filterable
            style="width: 100%;"
          >
            <el-option
              v-for="j in lesson"
              :key="j.lessonId"
              :value="j.lessonId"
              :label="j.lessonName"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classCompletionTimes"
          label="上课次数"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="clazz.classCompletionTimes"
            autocomplete="off"
            maxlength="20"
            show-word-limit
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          prop="classType"
          label="班级类型"
          :label-width="formLabelWidth"
        >
          <!-- <el-input v-model="clazz.classType" autocomplete="off" maxlength="20" show-word-limit style="width: 100%;" /> -->
          <el-select
            v-model="clazz.classType"
            placeholder="请选择"
            style="width:100%"
          >
            <el-option key="0" label="普通班级" value="0" />
            <el-option key="1" label="特殊班级" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="班级开始时间"
          :label-width="formLabelWidth"
          prop="startTimeToString"
        >
          <el-date-picker
            v-model="clazz.startTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          label="班级计划完成时间"
          :label-width="formLabelWidth"
          prop="endTimeToString"
        >
          <el-date-picker
            v-model="clazz.endTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          prop="classTimes"
          label="课时数量"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="clazz.classTimes"
            autocomplete="off"
            maxlength="20"
            show-word-limit
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          label="选择学生"
          :label-width="formLabelWidth"
          prop="studentId"
        >
          <el-select
            v-model="clazz.studentId"
            multiple
            placeholder="请选择"
            filterable=""
            style="width: 100%;"
          >
            <el-option
              v-for="j in student"
              :key="j.studentId"
              :value="j.studentId"
              :label="j.String"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classStatus"
          label="课程状态"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classStatus"
            placeholder="请选择"
            style="width:100%"
          >
            <el-option key="0" label="未开始" value="0" />
            <el-option key="1" label="已结束" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button
          v-if="editType == 2"
          type="primary"
          @click="handleUpdate('clazz')"
        >修 改</el-button>
        <el-button
          v-if="editType == 1"
          type="primary"
          @click="handleAddClass('clazz')"
        >添 加</el-button>
      </div>
    </el-dialog>
    <!-- -------------------------------------添加信息区-------------------------------------------------------------------- -->
  </div>
</template>
<script>
import {
  addClass,
  deleteClass,
  updateClass,
  getAllClass,
  getClassById,
  ClassIdSearch
} from '@/api/class'
import { getAllJurisdiction } from '@/api/jurisdiction'
import {
  getStaffStringR,
  getStaffStringD,
  getStaffStringT,
  getStaffStringM
} from '@/api/staff'
import { getAllLesson } from '@/api/lesson'
import { getAllStudentString } from '@/api/child'
import moment from 'moment'
export default {
  data() {
    return {
      readValue: '',
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      studentId: '',
      list: [],
      staff2: [],
      staff3: [],
      staff4: [],
      staff5: [],
      lesson: [],
      student: [],
      search: '',
      listLoading: false,
      dialogFormVisible: false,
      jurisdiction: [],
      editType: 1, // 1 添加 2 修改
      clazz: {},
      formLabelWidth: '200px',
      rules: {
        classCompletionTimes: [
          { required: true, message: '上课次数不能为空', trigger: 'blur' }
        ],
        classCourseId: [
          { required: true, message: '课程ID不能为空', trigger: 'blur' }
        ],
        classMedicalDirectorId: [
          { required: true, message: '医疗主管ID不能为空', trigger: 'blur' }
        ],
        classResponsibleTeacherId: [
          { required: true, message: '责任老师ID不能为空', trigger: 'blur' }
        ],
        classStatus: [
          { required: true, message: '课程状态不能为空', trigger: 'blur' }
        ],
        classTeacherId: [
          { required: true, message: '授课老师ID不能为空', trigger: 'blur' }
        ],
        classTeachingDirectorId: [
          { required: true, message: '教学主管ID不能为空', trigger: 'blur' }
        ],
        classTimes: [
          { required: true, message: '课时数量不能为空', trigger: 'blur' }
        ],
        classType: [
          { required: true, message: '班级类型不能为空', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '班级名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.fetchData()
    this.getAllJurisdiction()
    this.getAllStaffTeachingDirector()
    this.getAllStaffResponsibleTeacher()
    this.getAllStaffTeacher()
    this.getAllStaffMedicalDirectorr()
    this.getAllLesson()
    this.getAllStudent()
  },
  methods: {
    // 时间格式化
    dateFormat(row, column) {
      var date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 时间格式化

    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    getAllStaffTeachingDirector() {
      getStaffStringD().then(res => {
        console.log(res)
        this.staff2 = res.obj
      })
    },
    getAllStaffResponsibleTeacher() {
      getStaffStringR().then(res => {
        console.log(res)
        this.staff3 = res.obj
      })
    },

    getAllStaffTeacher() {
      getStaffStringT().then(res => {
        console.log(res)
        this.staff4 = res.obj
      })
    },
    getAllStaffMedicalDirectorr() {
      getStaffStringM().then(res => {
        console.log(res)
        this.staff5 = res.obj
      })
    },
    getAllLesson() {
      getAllLesson().then(res => {
        this.lesson = res.obj
      })
    },
    getAllStudent() {
      getAllStudentString().then(res => {
        this.student = res.obj
      })
    },
    fetchData() {
      this.listLoading = true
      getAllClass().then(data => {
        this.list = data.obj
        this.listLoading = false
      })
    },

    handleDelete(id) {
      this.$confirm('确认删除该班级？班级为' + id).then(() =>
        deleteClass(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil((this.list.length - 1) / this.pagesize)
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },

    handleAddClass(formName) {
      this.clazz.startTimeToString = this.clazz.startTime
      this.clazz.endTimeToString = this.clazz.endTime

      this.$refs[formName].validate(valid => {
        if (valid) {
          for (var i = 0; i < this.clazz.studentId.length; i++) {
            this.studentId += this.clazz.studentId[i] + ';'
          }
          this.clazz.studentId = this.studentId
          console.log(this.clazz)
          addClass(this.clazz).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.clazz = {}
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'erro，r'
          })
          return false
        }
      })
    },
    handleOpen(title, type, id) {
      this.clazz = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getClassById(id).then(resp => {
          console.log('resp的数据：', resp)
          this.clazz = resp.obj.clazz
          this.clazz.classStatus = String(this.clazz.classStatus)
          this.clazz.classType = String(this.clazz.classType)
          var list = this.clazz.studentId.split(';')
          list.length -= 1
          for (var i = 0; i < list.length; i++) {
            list[i] = parseInt(list[i])
          }
          console.log(list)
          this.clazz.studentId = list
        })
      }
    },
    handleClose() {
      this.dialogFormVisible = false
      this.clazz = {}
    },
    handleUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.studentId = ''
          for (var i = 0; i < this.clazz.studentId.length; i++) {
            this.studentId += this.clazz.studentId[i] + ';'
          }
          this.clazz.studentId = this.studentId
          console.log(this.clazz)

          updateClass(this.clazz).then(resp => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    ClassQuery() {
      console.log(this.search)
      ClassIdSearch(this.search).then(resp => {
        this.list = resp.obj
        this.currentPage = 1
      })
    },

    getAllJurisdiction() {
      getAllJurisdiction().then(resp => {
        this.jurisdiction = resp.obj0
      })
    }
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
  overflow: auto;
}
</style>
